package data_store

import (
	"fmt"
	"sync"
	"time"
	"zxs-micro-2/zxs-micro-balance-server/utils"
)

type LocalDataStore struct {
	IdDataMap map[string]*BalanceData
	TypeIds   map[string][]string
	skl       *utils.Skiplist
	mapLocks  sync.Mutex
}

func init() {
	d := new(LocalDataStore)
	d.IdDataMap = make(map[string]*BalanceData)
	d.TypeIds = make(map[string][]string)
	d.skl = utils.MakeSkiplist()
	GenerateDataStoreStruct("local", d)
	go d.timerDeleteNoHeartBeatService()
}

func (l *LocalDataStore) timerDeleteNoHeartBeatService() {
	for {
		tunix := time.Now().Unix()
		n := l.skl.GetFirstInScoreRange(0, tunix-10)
		if n == nil {
			<-time.After(time.Second * 10)
		} else {
			l.skl.Remove(n.Member, n.Score)
			fmt.Println(fmt.Sprintf("member=[%s]的节点最后心跳时间在：%s，已经超时",
				n.Member, time.Unix(n.Score, 0).String()))
		}
	}
}

func (l *LocalDataStore) AddService(data *BalanceData) {
	l.mapLocks.Lock()
	old, ok := l.IdDataMap[data.ServerId]
	if ok {
		//找到了同id信息，需要先删除跳表内的数据然后再写入
		l.skl.Remove(old.ServerId, old.HeartBeatTime)
	}
	l.IdDataMap[data.ServerId] = data
	tSlice, ok := l.TypeIds[data.ServerType]
	if !ok {
		tSlice = make([]string, 0)
	}
	if i := utils.SliceContain(tSlice, data.ServerId); i == -1 {
		tSlice = append(tSlice, data.ServerId)
	}
	l.TypeIds[data.ServerType] = tSlice
	l.skl.Insert(data.ServerId, data.HeartBeatTime)
	l.mapLocks.Unlock()
}

func (l *LocalDataStore) ServerHeartBeat(data *BalanceData) {
	l.AddService(data)
}

func (l *LocalDataStore) GetByIds(strings []string) []*BalanceData {
	rsp := make([]*BalanceData, 0)
	l.mapLocks.Lock()
	for _, o := range strings {
		data, ok := l.IdDataMap[o]
		if ok {
			rsp = append(rsp, data)
		}
	}
	l.mapLocks.Unlock()
	return rsp
}

func (l *LocalDataStore) GetByType(s string) []*BalanceData {
	return l.GetByIds(l.TypeIds[s])
}
